package com.tools.scanner.camera

import android.annotation.SuppressLint
import android.util.Log
import android.widget.Toast
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.view.LifecycleCameraController
import com.google.mlkit.common.MlKitException
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.common.InputImage
import com.tools.scanner.utils.QrCodeUtil

class CameraXAnalyzer(
    private val cameraController: LifecycleCameraController,
    private val callback: OnCameraCallback
) : ImageAnalysis.Analyzer {

    private var isEnable = true

    fun setEnable(value: Boolean) {
        isEnable = value
    }

    override fun analyze(image: ImageProxy) {
        if (!isEnable) {
            image.close()
            return
        }
        analyzeQrCode(image)
    }

    @SuppressLint("UnsafeOptInUsageError")
    private fun analyzeQrCode(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image
        if (mediaImage == null) {
            imageProxy.close()
            return
        }
        val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
        QrCodeUtil.processBitmap(image).addOnSuccessListener { result ->

        }.addOnFailureListener {

        }.addOnCompleteListener {
            var isSuccess = false
            if (it.isSuccessful && it.result.isNotEmpty()) {
                cameraController.unbind()
                isSuccess = true
            }
            mediaImage.close()
            imageProxy.close()
            if (isSuccess) {
                callback.onScanQrCodeSuccess(it.result[0])
            }
        }
    }
}